from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import Brand
from apps.meiduo_admin.serializers.brands import GoodsBrandSerializer
from apps.meiduo_admin.utils.pagination import MeiduoPagination


class GoodsBrandViewSet(ModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = GoodsBrandSerializer
    pagination_class = MeiduoPagination

    # 重写create方法 里面需要进行图片的上传
    def create(self, request, *args, **kwargs):
        image = request.data.get('logo')
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        # 验证
        # 验证
        if not all([name,image]):
            return Response({'detail': '数据不完整'}, status=400)
        # 处理 上传图片  创建图片对象

        image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        data = image_client.upload_by_buffer(image.read())

        image_name = data.get("Remote file_id")
        # 创建图片模型对象
        instance = Brand.objects.create(name=name, logo=image_name, first_letter=first_letter)

        serializer = self.get_serializer(instance)
        return Response(serializer.data, status=201)
    def update(self, request, *args, **kwargs):
        # 获取当前要修改的图片对象
        instance = self.get_object()
        print(type(instance.logo),instance.logo)
        print(type(instance.logo.name),instance.logo.name)
#<class 'django.db.models.fields.files.ImageFieldFile'> group1/M00/00/03/wKiTgF2udNeAbPJPAANS71lNjXQ5305340
#<class 'str'> group1/M00/00/03/wKiTgF2udNeAbPJPAANS71lNjXQ5305340
        # 接受
        logo = request.data.get('logo')
        name = request.data.get('name')
        first_letter = request.data.get('first_letter')
        #验证
        if not all([name,first_letter]):
            return Response({'detail':"数据不完整"},status=400)
        # 处理   删除图片 如果用户上传则修改  修改 删除后直接上传
        if logo:
            image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
            # 删除   instance.name   获取图片的名字字符串
            image_client.delete_file(instance.logo.name)
            # 上传
            data = image_client.upload_by_buffer(logo.read())
            print(data)
            instance.logo = data.get('Remote file_id')
        instance.name = name
        instance.save()
        instance.first_letter = first_letter
        instance.save()
        # 响应
        serializer = self.get_serializer(instance)
        return Response(serializer.data, status=201)

    def destroy(self, request, *args, **kwargs):
        # 查询当前对象
        instance = self.get_object()
        # 删除图片
        image_client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        image_client.delete_file(instance.logo.name)
        # 删除数据
        instance.delete()
        # 响应对象
        return Response(status=204)